package org.example.exampreparationtreasure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.example.exampreparationtreasure.enums.DifficultyLevel;
import org.example.exampreparationtreasure.enums.QuestionType;
import org.example.exampreparationtreasure.mapper.QuestionMapper;
import org.example.exampreparationtreasure.model.dto.QuestionQueryDTO;
import org.example.exampreparationtreasure.model.entity.Question;
import org.example.exampreparationtreasure.service.QuestionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@RequiredArgsConstructor
public class QuestionServiceImpl implements QuestionService {

    private final QuestionMapper questionMapper;

    @Override
    @Transactional
    public Long create(Question question) {
        try {
            // 验证必要字段
            if (question == null) {
                throw new IllegalArgumentException("题目对象不能为空");
            }
            if (question.getQuestionType() == null || question.getQuestionType().trim().isEmpty()) {
                throw new IllegalArgumentException("题目类型不能为空");
            }
            if (question.getCategoryId() == null) {
                throw new IllegalArgumentException("分类ID不能为空");
            }
            if (question.getCreatorId() == null) {
                throw new IllegalArgumentException("创建者ID不能为空");
            }
            
            // 转换题目类型为数据库枚举值（匹配数据库表结构）
            String questionType = question.getQuestionType();
            if (questionType != null) {
                switch (questionType) {
                    case "单选题":
                    case "单选":
                        question.setQuestionType("单选");
                        break;
                    case "多选题":
                    case "多选":
                        question.setQuestionType("多选");
                        break;
                    case "填空题":
                    case "填空":
                        question.setQuestionType("填空");
                        break;
                    case "简答题":
                    case "解答":
                        question.setQuestionType("解答");
                        break;
                    default:
                        // 如果已经是数据库枚举值，保持不变
                        if (questionType.matches("^(单选|多选|填空|解答)$")) {
                            // 已经是正确的枚举值，不需要转换
                        } else {
                            question.setQuestionType("单选"); // 默认单选
                        }
                        break;
                }
            }
            
            // 转换难度为数据库枚举值（匹配数据库表结构）
            String difficulty = question.getDifficulty();
            if (difficulty != null) {
                switch (difficulty) {
                    case "简单":
                    case "易":
                        question.setDifficulty("易");
                        break;
                    case "中等":
                    case "中":
                        question.setDifficulty("中");
                        break;
                    case "困难":
                    case "难":
                        question.setDifficulty("难");
                        break;
                    default:
                        // 如果已经是数据库枚举值，保持不变
                        if (difficulty.matches("^(易|中|难)$")) {
                            // 已经是正确的枚举值，不需要转换
                        } else {
                            question.setDifficulty("中"); // 默认中等
                        }
                        break;
                }
            } else {
                question.setDifficulty("中");
            }
            
            // 确保 questionContent 不为空，如果为空则设置默认值
            if (question.getQuestionContent() == null) {
                Map<String, Object> defaultContent = new HashMap<>();
                defaultContent.put("stem", "请输入题目内容");
                defaultContent.put("options", new ArrayList<>());
                defaultContent.put("answer", "");
                question.setQuestionContent(defaultContent);
            }
            
            // 设置新字段的默认值
            if (question.getQuestionAnswer() == null || question.getQuestionAnswer().trim().isEmpty()) {
                question.setQuestionAnswer("无答案");
            }
            if (question.getQuestionAnalysis() == null || question.getQuestionAnalysis().trim().isEmpty()) {
                question.setQuestionAnalysis("无解析");
            }
            if (question.getDeletedState() == null) {
                question.setDeletedState((byte) 0); // 0表示未删除
            }
            
            int result = questionMapper.insert(question);
            if (result > 0) {
        return question.getQuestionId();
            } else {
                throw new RuntimeException("插入题目失败，影响行数为0");
            }
        } catch (Exception e) {
            System.err.println("QuestionServiceImpl.create 发生异常: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public boolean update(Question question) {
        return questionMapper.updateById(question) > 0;
    }

    @Override
    public boolean delete(Long id) {
        Question toUpdate = new Question();
        toUpdate.setQuestionId(id);
        toUpdate.setDeletedState((byte) 1);
        return questionMapper.updateById(toUpdate) > 0;
    }

    @Override
    public Question getById(Long id) {
        return questionMapper.selectById(id);
    }

    @Override
    public List<Question> query(QuestionQueryDTO queryDTO) {
        if (queryDTO.getPageNum() == null || queryDTO.getPageNum() < 1) {
            queryDTO.setPageNum(1);
        }
        if (queryDTO.getPageSize() == null || queryDTO.getPageSize() < 1) {
            queryDTO.setPageSize(10);
        }
        queryDTO.setOffset((queryDTO.getPageNum() - 1) * queryDTO.getPageSize());
        return questionMapper.queryByConditions(queryDTO);
    }

    @Override
    public Long count(QuestionQueryDTO queryDTO) {
        return questionMapper.countByConditions(queryDTO);
    }

    @Override
    public String exportQuestionsToExcel(Long categoryId, QuestionType questionType, DifficultyLevel difficulty) {
        try {
            // 查询数据
            QueryWrapper<Question> wrapper = new QueryWrapper<>();
            if (categoryId != null) {
                wrapper.lambda().eq(Question::getCategoryId, categoryId);
            }
            if (questionType != null) {
                // 转换枚举为数据库值
                String dbQuestionType = convertQuestionTypeToDb(questionType.name());
                wrapper.lambda().eq(Question::getQuestionType, dbQuestionType);
            }
            if (difficulty != null) {
                // 转换枚举为数据库值
                String dbDifficulty = convertDifficultyToDb(difficulty.name());
                wrapper.lambda().eq(Question::getDifficulty, dbDifficulty);
            }
            // 排除逻辑删除
            wrapper.lambda().eq(Question::getDeletedState, (byte) 0);
            wrapper.lambda().orderByDesc(Question::getCreateTime);
            
            List<Question> questions = questionMapper.selectList(wrapper);
            
            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("题目列表");
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"题目ID", "题目类型", "题目内容", "难度", "创建者ID", "分类ID", "创建时间", "更新时间"};
            
            // 设置标题样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short) 12);
            headerStyle.setFont(headerFont);
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerStyle.setBorderBottom(BorderStyle.THIN);
            headerStyle.setBorderTop(BorderStyle.THIN);
            headerStyle.setBorderLeft(BorderStyle.THIN);
            headerStyle.setBorderRight(BorderStyle.THIN);
            
            // 创建标题单元格
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }
            
            // 设置数据样式
            CellStyle dataStyle = workbook.createCellStyle();
            dataStyle.setBorderBottom(BorderStyle.THIN);
            dataStyle.setBorderTop(BorderStyle.THIN);
            dataStyle.setBorderLeft(BorderStyle.THIN);
            dataStyle.setBorderRight(BorderStyle.THIN);
            dataStyle.setWrapText(true); // 自动换行
            
            // 填充数据
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < questions.size(); i++) {
                Question question = questions.get(i);
                Row row = sheet.createRow(i + 1);
                
                row.createCell(0).setCellValue(question.getQuestionId() != null ? question.getQuestionId() : 0);
                row.createCell(1).setCellValue(question.getQuestionType() != null ? question.getQuestionType() : "");
                row.createCell(2).setCellValue(question.getQuestionContent() != null ? question.getQuestionContent().toString() : "");
                row.createCell(3).setCellValue(question.getDifficulty() != null ? question.getDifficulty() : "");
                row.createCell(4).setCellValue(question.getCreatorId() != null ? question.getCreatorId() : 0);
                row.createCell(5).setCellValue(question.getCategoryId() != null ? question.getCategoryId() : 0);
                row.createCell(6).setCellValue(question.getCreateTime() != null ? question.getCreateTime().format(formatter) : "");
                row.createCell(7).setCellValue(question.getUpdateTime() != null ? question.getUpdateTime().format(formatter) : "");
                
                // 应用数据样式
                for (int j = 0; j < headers.length; j++) {
                    row.getCell(j).setCellStyle(dataStyle);
                }
            }
            
            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
                // 设置最小列宽
                if (sheet.getColumnWidth(i) < 3000) {
                    sheet.setColumnWidth(i, 3000);
                }
            }
            
            // 生成文件名
            String timestamp = java.time.LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String filename = "questions_export_" + timestamp + ".xlsx";
            
            // 确保data目录存在
            Path dataDir = Paths.get("src", "main", "resources", "data");
            if (!Files.exists(dataDir)) {
                Files.createDirectories(dataDir);
            }
            
            // 保存文件到data目录
            Path filePath = dataDir.resolve(filename);
            try (FileOutputStream fileOut = new FileOutputStream(filePath.toFile())) {
                workbook.write(fileOut);
            }
            workbook.close();
            
            return filePath.toString();
            
        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }

    @Override
    public Map<String, Object> importQuestions(List<Question> items) {
        int total = items == null ? 0 : items.size();
        int success = 0;
        if (items != null) {
            for (Question q : items) {
                if (create(q) != null) {
                    success++;
                }
            }
        }
        Map<String, Object> res = new HashMap<>();
        res.put("total", total);
        res.put("success", success);
        res.put("failed", total - success);
        return res;
    }
    
    /**
     * 转换题目类型枚举为数据库值
     */
    private String convertQuestionTypeToDb(String enumValue) {
        switch (enumValue) {
            case "SINGLE_CHOICE":
                return "单选";
            case "MULTIPLE_CHOICE":
                return "多选";
            case "FILL_IN_THE_BLANK":
                return "填空";
            case "SHORT_ANSWER":
                return "解答";
            case "JUDGMENT":
                return "单选"; // 判断题映射为单选
            default:
                return "单选";
        }
    }
    
    /**
     * 转换难度枚举为数据库值
     */
    private String convertDifficultyToDb(String enumValue) {
        switch (enumValue) {
            case "EASY":
                return "易";
            case "MEDIUM":
                return "中";
            case "HARD":
                return "难";
            default:
                return "中";
        }
    }
}


